package com.fametal.ui.service;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class QTService extends Service {
	public static final String TAG = "TAG";
	private static Boolean mainThreadFlag = true;
	public static Boolean ioThreadFlag = true;
	private ServerSocket serverSocket = null;
	private final int SERVER_PORT = 10086;

	@Override
	public void onCreate() {
		super.onCreate();
		Log.v(TAG, Thread.currentThread().getName() + "---->" + "  onCreate");
		/* 创建内部类sysBroadcastReceiver 并注册registerReceiver */
		new Thread() {
			public void run() {
				doListen();
			};
		}.start();
	}

	private void doListen() {
		Log.d(TAG, Thread.currentThread().getName() + "---->" + " doListen() START");
		serverSocket = null;
		try {
			Log.d(TAG, Thread.currentThread().getName() + "---->" + " doListen() new serverSocket");
			serverSocket = new ServerSocket(SERVER_PORT);
			while (mainThreadFlag) {
				Log.d(TAG, Thread.currentThread().getName() + "---->" + " doListen() listen");
				Socket client = serverSocket.accept();
				new Thread(new ThreadReadWriterIOSocket(this, client)).start();
			}
		} catch (IOException e1) {
			Log.v(TAG, Thread.currentThread().getName() + "---->" + "new serverSocket error");
			e1.printStackTrace();
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		// 关闭线程
		mainThreadFlag = false;
		// 关闭服务器
		try {
			Log.v(TAG, Thread.currentThread().getName() + "---->" + "serverSocket.close()");
			serverSocket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.v(TAG, Thread.currentThread().getName() + "---->" + "**************** onDestroy****************");
	}

	@Override
	public void onStart(Intent intent, int startId) {
		Log.d(TAG, Thread.currentThread().getName() + "---->" + " onStart()");
		super.onStart(intent, startId);

	}

	@Override
	public IBinder onBind(Intent arg0) {
		Log.d(TAG, "  onBind");
		return null;
	}

}